//
//  AppDelegate.swift
//  weibo117
//
//  Created by 宋禹奇 on 15/6/23.
//  Copyright © 2015年 宋禹奇. All rights reserved.
//

import UIKit
import AFNetworking

var sharedUserAccount = UserAccount.loadAccount()

//切换跟控制器的通知
let YUSwitchRootVCNotification = "YUSwitchRootVCNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
   

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
      
        
        setNetwork()
        setUpAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: YUSwitchRootVCNotification, object: nil)
        
        
        return true
    }
    
    //切换控制器
    func switchViewController(n: NSNotification){
    
        //判断 object是否为true 如果是  显示主界面
        let isMainVC = n.object as! Bool
        
        window?.rootViewController = isMainVC ? MainViewController() : WelcomeViewController()
    }

    //判断加载的默认控制器
    private func defaultViewController() -> UIViewController{
    
        //判断用户是否登录
        if sharedUserAccount != nil{
            return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
        }
        return MainViewController()
    }
    
    private func isNewUpdate() -> Bool{
    
        //1.获取应用程序当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let version = NSNumberFormatter().numberFromString(currentVersion)!.doubleValue
        //2.获取应用程序之前的版本,从用户偏好中读取
        let versionKey = "versionKey"
        let sandBoxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        //3.将当前版本 写入用户偏好
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: versionKey)
        
        return version > sandBoxVersion
        
  
    
    }
    
    //设置外观
    private func setUpAppearance(){
    
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()

    }
    
    private func setNetwork(){
        //设置网路指示器
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        
        //设置网路缓存
        let urlCache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        
        NSURLCache.setSharedURLCache(urlCache)
        

    }
    

}

